import { IPostJobPageReq, IPostJobPageRes, getJobRunJobNow, postJobDelete, postJobModifyStatus, postJobPage } from '@/api';
import {
  MciButton,
  MciDialog,
  MciLabel,
  MciMessage,
  MciPagination,
  MciSwitch,
  MciTable,
  MciTableColumn
} from '@/components/base';
import { ElLoading, ElPopconfirm, ElPopover, ElText } from 'element-plus';
import { JobDTO } from './type';
import { ExeAdd } from '../ExeAdd';
import TimedExecutionLog from '../TimedExecutionLog.vue';

export const ExeList = defineComponent({
  name: 'ExeList',
  setup() {
    // 表格数据
    const tableData = ref<JobDTO[]>([]);
    // 加载状态
    let loadingInstance: any = null;
    // 操作加载状态
    let delLoading = ref(false);
    let statusLoading = ref(false);
    let exeLoading = ref(false);
    // 新增任务
    let isVisible = ref(false);
    const exeAddRef = ref<InstanceType<typeof ExeAdd>>();
    let addTitle = ref('新增定时任务');
    // 确定新增任务
    const confirmHandle = () => {
      exeAddRef.value?.formValidate();
      // isVisible.value = false;
    };
    // 执行记录
    let recordVisible = ref(false);
    let currRowId = ref('');
    let currFlowIds = ref([]);

    setTimeout(() => {
      tableRequest();
    }, 1);

    // 获取数据
    const tableRequest = async () => {
      const exeListEl = document.getElementById('exe-list');
      if (exeListEl) {
        loadingInstance = ElLoading.service({
          target: exeListEl,
          body: false
        });
      }
      const params: IPostJobPageReq = {
        pageNo: currentPage.value,
        pageSize: pageSize.value
      };
      try {
        const data: IPostJobPageRes = await postJobPage(params);
        if (data && data.currentPage === currentPage.value) {
          tableData.value = data.list || [];
          pageTotal.value = data.total || 0;
        }
      } finally {
        loadingInstance?.close();
      }
    };
    // 翻页
    const currentPage = ref(1);
    const pageSize = ref(15);
    const small = ref(false);
    const background = ref(false);
    const disabled = ref(false);
    const pageTotal = ref(100);
    const handleSizeChange = (val: number) => {
      pageSize.value = val;
      currentPage.value = 1;
      tableRequest();
    };
    const handleCurrentChange = (val: number) => {
      currentPage.value = val;
      tableRequest();
    };

    // 刷新列表
    const refreshList = () => {
      currentPage.value = 1;
      tableRequest();
    };

    return () => {
      return (
        <div>
          <div class={'py-8 px-16 bg-white mb-8 flex justify-between'}>
            <MciLabel>定时任务</MciLabel>
            <MciButton
              icon="mci-icon-add"
              type="success"
              link={false}
              onClick={() => {
                // 新增
                addTitle.value = '新增定时任务';
                isVisible.value = true;
              }}>
              新增
            </MciButton>
          </div>
          <div id="exe-list" class="bg-white px-16 pb-16">
            <MciTable data={tableData.value}>
              <MciTableColumn label="任务ID" prop="id" minWidth={100} />
              <MciTableColumn label="扫描表" prop="tableName" minWidth={100} />
              <MciTableColumn
                label="是否全量扫描"
                prop="fullScan"
                minWidth={100}
                formatter={(row: JobDTO) => {
                  switch (row.fullScan) {
                    case 0:
                      return <ElText>否</ElText>;
                    case 1:
                      return <ElText type="success">是</ElText>;

                    default:
                      return <ElText>否</ElText>;
                  }
                }}
              />
              <MciTableColumn label="执行决策" prop="remark" minWidth={100} />
              <MciTableColumn label="CRON表达式" prop="cronExpression" minWidth={100} />
              <MciTableColumn
                label="状态"
                prop="status"
                minWidth={100}
                formatter={(row: JobDTO) => {
                  return (
                    <MciSwitch
                      modelValue={row.status}
                      active-value={1}
                      inactive-value={0}
                      onChange={async () => {
                        // 修改状态
                        try {
                          await postJobModifyStatus({
                            id: row.id,
                            status: row.status === 1 ? 0 : 1
                          });
                          tableRequest();
                        } catch (error) {
                          console.log(error);
                        } finally {
                          statusLoading.value = false;
                        }
                      }}
                    />
                  );
                }}
              />
              <MciTableColumn label="操作" minWidth={100}>
                {{
                  default: ({ row }: { row: JobDTO }) => {
                    return (
                      <div class={'flex items-center'}>
                        <MciButton
                          icon="mci-icon-edit-1"
                          type={'primary'}
                          link={true}
                          onClick={() => {
                            // 修改
                            addTitle.value = '修改定时任务';
                            isVisible.value = true;
                            setTimeout(() => {
                              nextTick(() => {
                                exeAddRef.value?.initData(row);
                              });
                            }, 1);
                          }}>
                          修改
                        </MciButton>
                        <div class="w-[1px] h-8 bg-gray-300 mx-2" />
                        <ElPopconfirm
                          width={200}
                          title="确定删除吗?"
                          confirm-button-text="确定"
                          cancel-button-text="取消"
                          onConfirm={async () => {
                            try {
                              row.id && (await postJobDelete({ id: row.id }));
                              refreshList();
                            } catch (error) {
                              console.log(error);
                            } finally {
                              delLoading.value = false;
                            }
                          }}>
                          {{
                            reference: () => {
                              return (
                                <MciButton loading={delLoading.value} icon="mci-icon-delete" type={'primary'} link={true}>
                                  删除
                                </MciButton>
                              );
                            }
                          }}
                        </ElPopconfirm>

                        <div class="w-[1px] h-8 bg-gray-300 mx-2" />

                        <ElPopover placement={'bottom'} width={160} trigger={'hover'}>
                          {{
                            reference: () => {
                              return (
                                <MciButton icon="mci-icon-a-chevron-rightdouble" type={'primary'} link={true}>
                                  更多
                                </MciButton>
                              );
                            },
                            default: () => {
                              return (
                                <div class="flex flex-col">
                                  {/* <div>
                                    <ElPopconfirm
                                      width={200}
                                      title={`确定执行${row.status === 1 ? '暂停' : '启用'}操作吗?`}
                                      confirm-button-text="确定"
                                      cancel-button-text="取消"
                                      onConfirm={async () => {
                                        // 修改状态
                                        try {
                                          await postJobModifyStatus({
                                            id: row.id,
                                            status: row.status === 1 ? 0 : 1
                                          });
                                          refreshList();
                                        } catch (error) {
                                          console.log(error);
                                        } finally {
                                          statusLoading.value = false;
                                        }
                                      }}>
                                      {{
                                        reference: () => {
                                          return (
                                            <MciButton
                                              icon={row.status === 1 ? 'mci-icon-pause-circle' : 'mci-icon-play-circle'}
                                              loading={statusLoading.value}
                                              type={'info'}
                                              link={true}>
                                              {row.status === 1 ? '暂停' : '启用'}
                                            </MciButton>
                                          );
                                        }
                                      }}
                                    </ElPopconfirm>
                                  </div> */}
                                  <div>
                                    <MciButton
                                      icon="mci-icon-play-circle"
                                      type={'info'}
                                      link={true}
                                      onClick={async () => {
                                        // 执行一次
                                        try {
                                          const data = await getJobRunJobNow({
                                            id: row.id
                                          });
                                          data && MciMessage.success('执行成功');
                                        } catch (error) {
                                          console.log(error);
                                        }
                                      }}>
                                      执行一次
                                    </MciButton>
                                  </div>
                                  <div>
                                    <MciButton
                                      icon="mci-icon-view-list"
                                      type={'info'}
                                      link={true}
                                      onClick={() => {
                                        // 查看执行记录
                                        currRowId.value = row?.id;
                                        currFlowIds.value = row?.flowIds || [];
                                        recordVisible.value = true;
                                      }}>
                                      执行记录
                                    </MciButton>
                                  </div>
                                </div>
                              );
                            }
                          }}
                        </ElPopover>
                      </div>
                    );
                  }
                }}
              </MciTableColumn>
            </MciTable>
            <MciPagination
              vModel:current-page={currentPage.value}
              vModel:page-size={pageSize.value}
              page-sizes={[10, 15, 20, 30, 50]}
              small={small.value}
              disabled={disabled.value}
              background={background.value}
              layout="total, sizes, prev, pager, next, jumper"
              total={pageTotal.value}
              onSize-change={(val: number) => handleSizeChange(val)}
              onCurrent-change={(val: number) => handleCurrentChange(val)}
            />
            {isVisible.value && (
              <MciDialog
                title={addTitle.value}
                modelValue={true}
                width={1000}
                draggable={true}
                customClass="max-height-dialog"
                onClose={() => {
                  isVisible.value = false;
                }}>
                {{
                  default() {
                    return (
                      <div class="flex flex-col">
                        <ExeAdd
                          ref={exeAddRef}
                          onClose={() => {
                            exeAddRef.value?.resetData();
                            isVisible.value = false;
                            refreshList();
                          }}
                        />
                      </div>
                    );
                  },
                  footer() {
                    return (
                      <>
                        <MciButton
                          onClick={() => {
                            exeAddRef.value?.resetData();
                            isVisible.value = false;
                          }}>
                          取消
                        </MciButton>
                        <MciButton type="primary" onClick={confirmHandle}>
                          确定
                        </MciButton>
                      </>
                    );
                  }
                }}
              </MciDialog>
            )}
            {recordVisible.value && (
              <MciDialog
                title={'执行记录'}
                modelValue={true}
                width={1000}
                draggable={true}
                appendToBody
                customClass="max-height-dialog"
                onClose={() => {
                  currRowId.value = '';
                  recordVisible.value = false;
                }}>
                {{
                  default() {
                    return (
                      <div>
                        <TimedExecutionLog jobId={currRowId.value} flowIds={currFlowIds.value} />
                      </div>
                    );
                  },
                  footer() {
                    return <div></div>;
                  }
                }}
              </MciDialog>
            )}
          </div>
        </div>
      );
    };
  }
});
